package com.example.mqtt_app;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttConnect;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.os.Bundle;
import android.widget.NumberPicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.button.MaterialButton;


//json 数据格式 数据上传
//{
//        "values": [1.2, 3.4, 5.6, 7.8, 9.0, 0.1],
//        "des": "示例描述"
//}

//json 数据格式 数据下发指令
//{
//        "switches": [true, false, true, false, true, false],
//        "operation_or_attribute": 1,
//}



@SuppressLint("UseSwitchCompatOrMaterialCode")
public class MainActivity extends AppCompatActivity {

    // 设备编号
    private String device_id = "device1";

    // mqtt变量
    private MqttClient client;
    private MqttConnectOptions options;

    private String host = "tcp://broker-cn.emqx.io:1883";
    private String userName = "";
    private String passWord = "";
    private String mqtt_id = "my_device_id/qsy/%s";
    private String topic_sub = "my_device_sub/qsy/%s"; // 设备订阅主题
    private String topic_pub = "my_device_send/qsy/%s"; // 设备发送主题



    private Handler handler; // 处理handler消息
    private ScheduledExecutorService scheduler; // 定时器

    // 数据参数展示
    private TextView value1;
    private TextView value2;
    private TextView value3;
    private TextView value4;
    private TextView value5;
    private TextView value6;

    private TextView test_text;

    // 开关状态
    private Switch switch1;
    private Switch switch2;
    private Switch switch3;

    // 布局中的按钮
    private Button connectButton; // 连接按钮
    private Button disconnectButton; // 断开按钮

    // 连接状态标志
    private boolean isConnected = false; // 默认为断开状态



    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 界面打开后最先开始运行
        super.onCreate(savedInstanceState); // 调用父类方法
        EdgeToEdge.enable(this); // 开启EdgeToEdge效果
        setContentView(R.layout.activity_main); // 加载布局文件


        // 获取value1到value6的TextView
        TextView value1 = findViewById(R.id.value1);
        TextView value2 = findViewById(R.id.value2);
        TextView value3 = findViewById(R.id.value3);
        TextView value4 = findViewById(R.id.value4);
        TextView value5 = findViewById(R.id.value5);
        TextView value6 = findViewById(R.id.value6);


        // 设置value1到value6的值
        value1.setText("0");
        value2.setText("0");
        value3.setText("0");
        value4.setText("0");
        value5.setText("0");
        value6.setText("0");

        // 找到这三个Switch组件
        switch1 = findViewById(R.id.switch1);
        switch2 = findViewById(R.id.switch2);
        switch3 = findViewById(R.id.switch3);



        // 为每个Switch组件设置监听器
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 处理开关1状态改变的逻辑
                TextView switch1Text = findViewById(R.id.testTextView); // 假设你有一个TextView来显示状态
                switch1Text.setText(isChecked ? "开关1: 开启" : "开关1: 关闭");
                // 发送mqtt指令
                boolean[] switches = {isChecked};
                sendCommand(switches, 1);
            }
        });

        switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 处理开关2状态改变的逻辑
                TextView switch2Text = findViewById(R.id.testTextView); // 假设你有一个TextView来显示状态
                switch2Text.setText(isChecked ? "开关2: 开启" : "开关2: 关闭");
                // 发送mqtt指令
                boolean[] switches = {isChecked};
                sendCommand(switches, 2);
            }
        });

        switch3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 处理开关3状态改变的逻辑
                TextView switch3Text = findViewById(R.id.testTextView); // 假设你有一个TextView来显示状态
                switch3Text.setText(isChecked ? "开关3: 开启" : "开关3: 关闭");
                // 发送mqtt指令
                boolean[] switches = {isChecked};
                sendCommand(switches, 3);
            }
        });


        // 以下是mqtt---------------------------

        //初始化mqtt
        Mqtt_init();
//        startReconnect();


        // 初始化按钮
        // 初始化按钮
        connectButton = findViewById(R.id.connectButton);
        disconnectButton = findViewById(R.id.disconnectButton);

        // 设置按钮点击事件
        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 如果已连接，直接返回
                if (isConnected) {
                    return;
                }

                // 启动连接
                Mqtt_connect();

                // 更新按钮状态
                updateButtonState(true);
            }
        });

        disconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 如果已断开，直接返回
                if (!isConnected) {
                    return;
                }

                // 断开连接
                try {
                    if (client != null && client.isConnected()) {
                        client.disconnect();
                        startReconnect(); // 重连机制
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                }

                // 更新按钮状态
                updateButtonState(false);
            }
        });





        // handler 处理消息
        handler = new Handler(Looper.getMainLooper()) {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:  // 开机校验更新回传
                        break;
                    case 2: // 反馈回传
                        break;
                    case 3: // 收到消息回传
                        // 弹出收到的消息
                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        // 使用orgjson解析json数据
                        try {
                            // 解析json数据
                            JSONObject jsonObject = new JSONObject((String) msg.obj);

                            //json 数据格式 数据上传
                            //{
                            //        "values": [1.2, 3.4, 5.6, 7.8, 9.0, 0.1],
                            //        "des": "示例描述"
                            //}

                            // 解析数据
                            double[] values = new double[6];
                            String des = "";
                            boolean operation_or_attribute = false;
                            if(jsonObject.has("values"))
                            {
                                JSONArray jsonArray = jsonObject.getJSONArray("values");
                                for(int i=0;i<jsonArray.length();i++)
                                {
                                    values[i] = jsonArray.getDouble(i);
                                }
                            }
                            if(jsonObject.has("des"))
                            {
                                des = jsonObject.getString("des");
                            }

                            // 弹出收到的消息
//                            Toast.makeText(MainActivity.this, "收到数据：" + des, Toast.LENGTH_SHORT).show();
                            // 更新界面显示
                            value1.setText(String.valueOf(values[0]));
                            value2.setText(String.valueOf(values[1]));
                            value3.setText(String.valueOf(values[2]));
                            value4.setText(String.valueOf(values[3]));
                            value5.setText(String.valueOf(values[4]));
                            value6.setText(String.valueOf(values[5]));


                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }


                        break;
                    case 30:  //连接失败
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 31:  //连接成功
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        // 订阅主题
                        try {
                            // topic_sub+device_id 组合字符串
                            String topic_sub_id = String.format(topic_sub, device_id);

                            // 弹出显示订阅主题
//                            Toast.makeText(MainActivity.this, topic_sub_id, Toast.LENGTH_SHORT).show();

                            client.subscribe(topic_sub_id,1);
                        } catch (MqttException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    default:
                        break;
                }
            }
        };


    }





    private String[] getDisplayedValues(int minValue, int maxValue, int step) {
        int count = (maxValue - minValue) / step + 1;
        String[] displayedValues = new String[count];
        for (int i = 0; i < count; i++) {
            displayedValues[i] = String.valueOf(minValue + i * step);
        }
        return displayedValues;
    }

    //Mqtt初始化函数
    private void Mqtt_init()
    {
        try {
            // 组合设备mqtt_id
            mqtt_id = String.format(mqtt_id, device_id);
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    //startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    // 组合订阅主题
                    String topic_sub_id = String.format(topic_sub, device_id);
                    if(topicName.equals(topic_sub_id))
                    {
                        //收到温度数据
                        msg.what = 3;   //收到消息标志位
                        msg.obj = new String(message.getPayload()); // 收到的消息内容
                        handler.sendMessage(msg);    // hander 回传
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //MQTT连接EMQ-X函数
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message(); // 连接成功标志位
                        msg.what = 31; // 连接成功标志位
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30; // 连接失败标志位
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    //MQTT重连
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    // 构造下发json数据函数，
    //json 数据格式 数据下发指令
    //{
    //        "switches": [true, false, true, false, true, false],
    //        "index": 1,
    //}
    // 构造json数据index是数组的下标
    private String constructJsonData(boolean[] switches, int index){
        String jsonData = "";
        JSONObject jsonObject = new JSONObject();
        try {
            // 构造json数据
            JSONArray jsonArray = new JSONArray();
            for(int i=0;i<switches.length;i++)
            {
                jsonArray.put(switches[i]);
            }
            jsonObject.put("switches", jsonArray);
            jsonObject.put("index", index);
            jsonData = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonData;
    }

    // 发送指令函数
    private void sendCommand(boolean[] switches, int index){
        String jsonData = constructJsonData(switches, index);
        MqttMessage message = new MqttMessage(jsonData.getBytes());
        message.setQos(1);
        try {
            String topic_pub_id = String.format(topic_pub, device_id);
            client.publish(topic_pub_id, message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    // 更新按钮状态
    private void updateButtonState(boolean isConnected) {
        this.isConnected = isConnected;

        if (isConnected) {
            // 已连接
            connectButton.setEnabled(false); // 禁用连接按钮
            disconnectButton.setEnabled(true); // 启用断开按钮
            Toast.makeText(this, "已连接", Toast.LENGTH_SHORT).show();
        } else {
            // 未连接
            connectButton.setEnabled(true); // 启用连接按钮
            disconnectButton.setEnabled(false); // 禁用断开按钮
            Toast.makeText(this, "已断开", Toast.LENGTH_SHORT).show();
        }
    }

}


















